package com.taoz.mianshiwa.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.db.Db;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taoz.mianshiwa.common.BaseResponse;
import com.taoz.mianshiwa.common.DeleteRequest;
import com.taoz.mianshiwa.common.ErrorCode;
import com.taoz.mianshiwa.common.ResultUtils;
import com.taoz.mianshiwa.constant.UserConstant;
import com.taoz.mianshiwa.exception.ThrowUtils;
import com.taoz.mianshiwa.model.dto.questionBankQuestion.QuestionBankQuestionAddRequest;
import com.taoz.mianshiwa.model.dto.questionBankQuestion.QuestionBankQuestionBatchRequest;
import com.taoz.mianshiwa.model.dto.questionBankQuestion.QuestionBankQuestionQueryRequest;
import com.taoz.mianshiwa.model.dto.questionBankQuestion.QuestionBankQuestionUpdateRequest;
import com.taoz.mianshiwa.model.entity.Question;
import com.taoz.mianshiwa.model.entity.QuestionBank;
import com.taoz.mianshiwa.model.entity.QuestionBankQuestion;
import com.taoz.mianshiwa.model.vo.QuestionBankQuestionVO;
import com.taoz.mianshiwa.service.QuestionBankQuestionService;
import com.taoz.mianshiwa.service.QuestionBankService;
import com.taoz.mianshiwa.service.QuestionService;
import com.taoz.mianshiwa.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 题库接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/questionBankQuestion")
@Slf4j
public class QuestionBankQuestionController {

    @Resource
    private QuestionBankQuestionService questionBankQuestionService;
    @Resource
    private QuestionBankService questionBankService;
    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    /**
     * 分页获取题库列表（封装类）
     *
     * @param questionBankQuestionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionBankQuestionVO>> listQuestionBankQuestionVOByPage(@RequestBody QuestionBankQuestionQueryRequest questionBankQuestionQueryRequest,
                                                                                       HttpServletRequest request) {
        long current = questionBankQuestionQueryRequest.getCurrent();
        long size = questionBankQuestionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionBankQuestion> questionBankQuestionPage = questionBankQuestionService.page(new Page<>(current, size),
                questionBankQuestionService.getQueryWrapper(questionBankQuestionQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionBankQuestionService.getQuestionBankQuestionVOPage(questionBankQuestionPage, request));
    }

    @PostMapping("/add/batch")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> batchAddQuestionsToBank(@RequestBody QuestionBankQuestionBatchRequest questionBankQuestionBatchAddRequest, HttpServletRequest request) {
        Long questionBankId = questionBankQuestionBatchAddRequest.getQuestionBankId();
        List<Long> questionIdList = questionBankQuestionBatchAddRequest.getQuestionIdList();

        questionBankQuestionService.batchAddQuestionsToBank(questionBankId, questionIdList);

        return ResultUtils.success(true);
    }

    @PostMapping("/delete/batch")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> batchDeleteQuestionsFromBank(@RequestBody QuestionBankQuestionBatchRequest questionBankQuestionBatchAddRequest) {
        Long questionBankId = questionBankQuestionBatchAddRequest.getQuestionBankId();
        List<Long> questionIdList = questionBankQuestionBatchAddRequest.getQuestionIdList();

        questionBankQuestionService.batchDeleteQuestionsFromBank(questionBankId, questionIdList);

        return ResultUtils.success(true);
    }

    /**
     * 创建题库
     *
     * @param questionBankQuestionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addQuestionBankQuestion(@RequestBody QuestionBankQuestionAddRequest questionBankQuestionAddRequest, HttpServletRequest request) {
        // 参数校验
        Long questionBankId = questionBankQuestionAddRequest.getQuestionBankId();
        Long questionId = questionBankQuestionAddRequest.getQuestionId();
        ThrowUtils.throwIf(questionId == null || questionBankId == null, ErrorCode.PARAMS_ERROR);
        Question question = questionService.getById(questionId);
        ThrowUtils.throwIf(question == null, ErrorCode.PARAMS_ERROR);
        QuestionBank questionBank = questionBankService.getById(questionBankId);
        ThrowUtils.throwIf(questionBank == null, ErrorCode.PARAMS_ERROR);

        QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
        BeanUtils.copyProperties(questionBankQuestionAddRequest, questionBankQuestion);
        questionBankQuestion.setUserId(StpUtil.getLoginIdAsLong());
        // 写入数据库
        boolean result = questionBankQuestionService.save(questionBankQuestion);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(questionBankQuestion.getId());
    }

    /**
     * 删除题库
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestionBankQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest.getId() == null, ErrorCode.PARAMS_ERROR);

        boolean result = questionBankQuestionService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(true);
    }

    /**
     * 删除题库
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete/QQ")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteQuestionBankQuestionByQQ(@RequestBody DeleteRequest deleteRequest) {
        ThrowUtils.throwIf(deleteRequest.getQuestionId() == null || deleteRequest.getQuestionBankId() == null, ErrorCode.PARAMS_ERROR);

        Long questionBankId = deleteRequest.getQuestionBankId();
        Long questionId = deleteRequest.getQuestionId();
        // 判断是否存在
        QuestionBankQuestion questionBankQuestion = questionBankQuestionService.lambdaQuery()
                .eq(QuestionBankQuestion::getQuestionBankId, questionBankId)
                .eq(QuestionBankQuestion::getQuestionId, questionId)
                .one();
        ThrowUtils.throwIf(questionBankQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = questionBankQuestionService.removeById(questionBankQuestion.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(true);
    }

    /**
     * 更新题库（仅管理员可用）
     *
     * @param questionBankQuestionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestionBankQuestion(@RequestBody QuestionBankQuestionUpdateRequest questionBankQuestionUpdateRequest) {
        ThrowUtils.throwIf(questionBankQuestionUpdateRequest.getId() == null || questionBankQuestionUpdateRequest.getQuestionId() == null || questionBankQuestionUpdateRequest.getQuestionBankId() == null, ErrorCode.PARAMS_ERROR);

        QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
        BeanUtils.copyProperties(questionBankQuestionUpdateRequest, questionBankQuestion);
        // 操作数据库
        boolean result = questionBankQuestionService.updateById(questionBankQuestion);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取题库（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionBankQuestionVO> getQuestionBankQuestionVOById(Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);

        // 查询数据库
        QuestionBankQuestion questionBankQuestion = questionBankQuestionService.getById(id);
        ThrowUtils.throwIf(questionBankQuestion == null, ErrorCode.NOT_FOUND_ERROR);

        // 获取封装类
        return ResultUtils.success(questionBankQuestionService.getQuestionBankQuestionVO(questionBankQuestion, request));
    }
}
